/*
 * Essa classe é responsável por conectar, realizar pesquisas
 * no Banco de dados.
 * 
 */
package javagenda;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.DefaultTableModel;
/**
 *
 * @author gbf
 */
public class BancoDeDados {

    Connection con = null;
    
    public  void conecta() {
        try {
            Class.forName("org.postgresql.Driver");           
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(BancoDeDados.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            con = DriverManager.getConnection("jdbc:postgresql://localhost:5432/teste" ,"postgres", "postgres");
        } catch (SQLException ex) {
            Logger.getLogger(BancoDeDados.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
    
    public void query_lista(DefaultTableModel model){
        
        
        String query = "select * from contatos"; 
        
        Statement stmt; 
        try {
            stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery(query);
            ResultSetMetaData rsmd = rs.getMetaData(); 
            int colunas = rsmd.getColumnCount();
        
            while (rs.next()) { 
                model.addRow(new Object[] {rs.getString(2), rs.getString(3)  , rs.getString(4)});
            }
        } catch (SQLException ex) {
            Logger.getLogger(BancoDeDados.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public void query_insere(String nome, String telefone, String celular){
        String query = "INSERT INTO contatos VALUES (DEFAULT, '%s' , '%s', '%s' )";
        query = String.format(query, nome, telefone, celular);
        Statement stmt;
        try {
            stmt = con.createStatement();
            int i = stmt.executeUpdate(query);
        } catch (SQLException ex) {
            Logger.getLogger(BancoDeDados.class.getName()).log(Level.SEVERE, null, ex);
        }
       
    }
    
    public void query_remove(String nome, String telefone, String celular){
        String query = "DELETE FROM contatos WHERE nome = '%s' AND telefone = '%s' AND celular = '%s'";
        query = String.format(query, nome, telefone, celular);
        Statement stmt;
        try {
            stmt = con.createStatement();
            int i = stmt.executeUpdate(query);
        } catch (SQLException ex) {
            Logger.getLogger(BancoDeDados.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}